//
//  KFOrderVC.m
//  KafeeSale
//
//  Created by Liboom on 2025/6/8.
//

#import "KFOrderVC.h"
#import "KFOrderCell.h"

#import "YBPopupMenu.h"
@interface KFOrderVC ()<UITableViewDelegate,UITableViewDataSource,YBPopupMenuDelegate>
@property(nonatomic, assign) NSInteger  page;
@property(nonatomic, strong) NSMutableArray *dataArr;
@property(nonatomic, strong) UITableView *myTab;
@property(nonatomic, assign) NSInteger curState;
@end

@implementation KFOrderVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.myTitle = @"订单";
    self.rightBtnName = @"排序";
    self.rightBtnFontSize=14;
    self.rightBtnNameColor = UIColor.blackColor;
    self.page = 1;
    self.curState = -1;
    self.dataArr = [NSMutableArray new];
    [self.view addSubview:self.myTab];
}
-(void)rightBtnClick{
    [YBPopupMenu showRelyOnView:self.rightBtn titles:@[@"全部",@"出餐中"] icons:nil menuWidth:80 otherSettings:^(YBPopupMenu *popupMenu) {
        popupMenu.delegate = self;
    }];
}
- (void)ybPopupMenu:(YBPopupMenu *)ybPopupMenu didSelectedAtIndex:(NSInteger)index{
    if (index == 0) {
        self.curState = 2;
    }else if(index == 1){
        self.curState = 4;
    }
    self.page = 1;
    [self finalGetData];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self finalGetData];
}
-(void)getData{
    XHQHUDInView(self.view);
    NSString * url = [WorkUrl returnURL:Interface_For_Get_Beans_Data];
    [PGNetworkHelper GET:url parameters:nil cache:NO headers:[Mytools getHeaders] responseCache:nil success:^(id responseObject) {
        if ([responseObject[@"code"] integerValue]==200) {
            VicSingleObject * single = [VicSingleObject getInstance];
            single.beansList = responseObject[@"data"];
            [self finalGetData];
        }else{
            XHQHUDErrorText(responseObject[@"message"]);
        }
    } failure:^(id error) {
        XHQHUDErrorText(error[@"msg"]);
    }];
}
-(void)finalGetData{
    NSDictionary * data = [self configDate];
    
    NSMutableDictionary *dic = @{@"adminId":[Mytools getUserId],@"startTime":data[@"zero"],@"endTime":data[@"cur"],@"current":@(1),@"size":@(9999)}.mutableCopy;
    if (self.curState == 2) {
        [dic setObject:@"2,4,5" forKey:@"stateStr"];
    }else if(self.curState == 4){
        [dic setObject:@"2,4" forKey:@"stateStr"];
    }
    [PGNetworkHelper GET:[WorkUrl returnURL:Interface_For_Order_List]
              parameters:dic
                  cache:NO
                headers:[Mytools getHeaders]
          responseCache:nil
                success:^(id responseObject) {
        XHQHUDHide();
        [self.myTab.mj_header endRefreshing];
        
        if ([responseObject[@"code"] integerValue] == 200) {
            NSDictionary *dict = responseObject[@"data"] ?: @{};
            
            // 分页逻辑处理
            NSInteger totalCount = [dict[@"total"] integerValue]; // 总数据条数
            NSInteger pageSize = 10; // 每页固定10条
            
            // 计算总页数（向上取整）
            NSInteger totalPages = (totalCount + pageSize - 1) / pageSize;
            
            // 判断是否还有更多数据
            if (self.page >= totalPages) {
                [self.myTab.mj_footer endRefreshingWithNoMoreData];
            } else {
                // 重置footer状态，避免"无更多数据"状态永久存在
                [self.myTab.mj_footer resetNoMoreData];
            }
            
            // 处理数据：首次加载直接赋值，后续加载追加数据
            NSArray *newModels = [KFOrderModel mj_objectArrayWithKeyValuesArray:dict[@"records"]] ?: @[];
            NSInteger startIndex = (self.page - 1) * 10; // 每页10条
               
            // 设置新数据的序号
            for (NSInteger i = 0; i < newModels.count; i++) {
               KFOrderModel *model = newModels[i];
               model.serialNumber = startIndex + i + 1; // 序号从1开始
            }
            if (self.page == 1) {
                // 第一页：重置数据
                self.dataArr = newModels.mutableCopy;
            } else {
                // 后续页：追加数据
                NSMutableArray *temp = [NSMutableArray arrayWithArray:self.dataArr];
                [temp addObjectsFromArray:newModels];
                self.dataArr = temp;
            }
            
            [self.myTab reloadData];
            
        } else {
            XHQHUDErrorText(responseObject[@"msg"]);
        }
    } failure:^(id error) {
        XHQHUDHide();
        [self.myTab.mj_header endRefreshing];
        
        // 上拉加载失败时回滚页码
        if (self.page > 1) {
            self.page--;
        }
    }];
}
-(NSDictionary*)configDate{
    NSTimeZone *beijingTimeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [NSTimeZone setDefaultTimeZone:beijingTimeZone];
    
    // 2. 获取当前时间（基于北京时区）
    NSDate *now = [NSDate date];
    
    // 3. 获取北京时区今天的0点时间
    NSCalendar *calendar = [NSCalendar currentCalendar];
    calendar.timeZone = beijingTimeZone;
    NSDateComponents *components = [calendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:now];
    components.hour = 0;
    components.minute = 0;
    components.second = 0;
    NSDate *todayZero = [calendar dateFromComponents:components];
    
    // 4. 计算时间差
    NSTimeInterval interval = [now timeIntervalSinceDate:todayZero];
    NSInteger totalSeconds = (NSInteger)interval;
    NSInteger hours = totalSeconds / 3600;
    NSInteger minutes = (totalSeconds % 3600) / 60;
    NSInteger seconds = totalSeconds % 60;
    
    // 5. 格式化输出（使用24小时制 + 北京时区）
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss"; // HH 表示24小时制
    formatter.timeZone = beijingTimeZone;
    
    NSString *currentTime = [formatter stringFromDate:now];
    NSString *zeroTime = [formatter stringFromDate:todayZero];
    return @{@"zero":zeroTime,@"cur":currentTime};
}
#pragma mark 代理方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    KFOrderCell * cell = [tableView dequeueReusableCellWithIdentifier:@"KFOrderCell"];
    if (!cell) {
        cell = [[KFOrderCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"KFOrderCell"];
    }
    KFOrderModel * mo = self.dataArr[indexPath.row];
    cell.model = mo;
    __weak typeof(self)weakSelf = self;
    cell.reloadBlock = ^{
        weakSelf.page = 1;
        [weakSelf.dataArr removeAllObjects];
        [weakSelf getData];
    };
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    KFOrderModel * mo = self.dataArr[indexPath.row];
    CGFloat height = [tableView cellHeightForIndexPath:indexPath model:mo keyPath:@"model" cellClass:[KFOrderCell class] contentViewWidth:SCREEN_WIDTH];
    return height;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   
}
- (UITableView *)myTab {
    if (!_myTab) {
        _myTab = [[UITableView alloc] initWithFrame:Frame(0, kTopHeight, SCREEN_WIDTH, SCREEN_HEIGHT-kTopHeight-kTabbarHeight) style:UITableViewStyleGrouped];
        _myTab.dataSource = self;
        _myTab.delegate = self;
        [_myTab registerClass:[KFOrderCell class] forCellReuseIdentifier:@"KFOrderCell"];
        _myTab.backgroundColor = UnderLineColor;
        _myTab.separatorStyle = UITableViewCellSeparatorStyleNone;
        __weak typeof(self)weakSelf = self;
        _myTab.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            weakSelf.page = 1;
            [weakSelf.dataArr removeAllObjects];
            [weakSelf getData];
        }];
    }
    return _myTab;
}

@end
